package a66weding.com.jiehuntong.activity.home.hotel.shop;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Paint;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;
import org.xutils.x;

import a66weding.com.jiehuntong.R;
import a66weding.com.jiehuntong.activity.LoginActivity;
import a66weding.com.jiehuntong.activity.ShopDetailsActivity;
import a66weding.com.jiehuntong.activity.me.MeShoppingCartActivity;
import a66weding.com.jiehuntong.application.DataWareHourse;
import a66weding.com.jiehuntong.application.GlobalApplication;
import a66weding.com.jiehuntong.beans.AddCartResultBean;
import a66weding.com.jiehuntong.beans.CancelCollectBean;
import a66weding.com.jiehuntong.beans.CommonResultBean;
import a66weding.com.jiehuntong.beans.ErrorBean;
import a66weding.com.jiehuntong.beans.HomeParticularsBean;
import a66weding.com.jiehuntong.beans.HttpRequestBean;
import a66weding.com.jiehuntong.beans.MeShoppingCartDeleteBean;
import a66weding.com.jiehuntong.beans.SuccessBean;
import a66weding.com.jiehuntong.beans.User;
import a66weding.com.jiehuntong.common.MessageEvent;
import a66weding.com.jiehuntong.common.api.Url;
import a66weding.com.jiehuntong.common.utils.CUtils;
import a66weding.com.jiehuntong.common.utils.ImageOptionsUtil;
import a66weding.com.jiehuntong.http.HttpHandleUtil;
import a66weding.com.jiehuntong.http.OnNetResultListener;
import a66weding.com.jiehuntong.http.RequestCode;
import a66weding.com.jiehuntong.http.UrlDealUtil;
import a66weding.com.jiehuntong.inner.ToNextInnner;
import a66weding.com.jiehuntong.view.ConfirmLoginDialog;
import a66weding.com.jiehuntong.widgets.dialog.MyDialog;

/**
 * Created by admin on 2016/9/12.
 * 作用：首页面商品详情
 */
public class HomeProductdetailActivity extends FragmentActivity implements View.OnClickListener, ToNextInnner, OnNetResultListener {
    private ViewGroup mContentLay;
    private LinearLayout mNonetLay;
    private LinearLayout mProgressLay;
    private View view;
    private McoySnapPageLayout mcoySnapPageLayout = null;
    private McoyProductContentPage bottomPage = null;
    private McoyProductDetailInfoPage topPage = null;
    private TextView title1;
    private TextView title2;
    private ShopTuWenFragment homeTaocanFragment1;
    private HotPackageFragment hotPackageFragment;
    private final int BASE_REQUEST_LOGIN_CODE = 7000;
    //fragment 管理者;
    //是否登录
    private boolean isLogin;
    //产品id;
    private int producti_id;
    //用户对象
    private User.DataBean userBean;
    private User user;
    private int i_category = 0;
    //topView
    private View topView;
    //头部图片
    private ImageView iv_detailhead;
    //店铺简介
    private TextView tv_nvc_Name;
    //店铺名称
    private TextView tv_nvc_StoreName;
    //售价
    private TextView tv_productdetail_price;
    //原价
    private TextView tv_nvc_shopPrice;
    //店铺logo;
    private ImageView iv_lable_shope;
    //logo 名称
    private TextView tv_nvc_shopName;
    //logo地址
    private TextView tv_nvc_Address;
    //案例
    private TextView tv_example;
    //粉丝数
    private TextView tv_collections;
    //tv_product_desc 套餐描述;
    private TextView tv_product_desc;
    private HomeParticularsBean.DataBean homedata;
    //是否展开
    private boolean isExpend = false;
    //展开的按钮
    private ImageView iv_product_taocanExpend;
    //进入店铺按钮
    private ImageView iv_detail_toshop;
    //产品上架数量
    private int I_Show;
    //添加购物车
    private TextView tv_addcart;
    //收藏
    private LinearLayout ll_me_collect;
    //是否收藏
    private boolean IsCollection;
    //白心
    private ImageView iv_me_no;
    //红心
    private ImageView iv_me_show;
    //立即购买
    private TextView tv_addcart_buynow;
    //打电话
    private TextView tv_addcart_phone;
    //pupowindow;
    private PopupWindow mPopWindow;
    //购物车标题栏
    private LinearLayout lay_cart_addcart;
    //购物车图标]
    private TextView tv_addcart_cart;
    protected static final int HAVEDATA = 1;
    protected static final int NODATA = 0;
    protected static final int DATAERROR = 2;
    protected static final int NONET = 4;
    //返回键
    private LinearLayout product_detail_onback;
    private final int DIALOG = 1;
    private MyDialog myDialog;

    private boolean isCanBuy = true;
    private boolean isCanBuyNow = true;
    private boolean isShowError;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case DIALOG:
                    if (myDialog != null) {
                        myDialog.dismiss();
                    }
                    break;
            }
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
     isCanBuy = true;
     isCanBuyNow = true;
        setContentView(R.layout.activity_shopactivity);
        Intent intent = getIntent();
        if (intent != null) {
            producti_id = intent.getIntExtra("productId", 144);
        }
        isLogin = ((GlobalApplication) getApplication()).isLogin();
        if (isLogin()) {
            user = DataWareHourse.getInstance().getmUser();
            userBean = user.getData().get(0);
        }
        initView();
        mContentLay = mcoySnapPageLayout = (McoySnapPageLayout) findViewById(R.id.flipLayout);
        topView = View.inflate(this, R.layout.mcoy_produt_detail_layout, null);
        setData();
        //获取数据;
        getHomeData();
        topPage = new McoyProductDetailInfoPage(HomeProductdetailActivity.this, topView);
        init(savedInstanceState);
        addView();
    }

    private void initView() {
        view = View.inflate(this, R.layout.mcoy_product_content_page, null);
        mProgressLay = (LinearLayout) findViewById(R.id.lay_progress);
        mNonetLay = (LinearLayout) findViewById(R.id.lay_nonet);
        mNonetLay.setOnClickListener(this);
        title1 = (TextView) view.findViewById(R.id.shop_title1);
        title1.setTextColor(getResources().getColor(R.color.colorMainRed));
        title1.setOnClickListener(this);
        title2 = (TextView) view.findViewById(R.id.shop_title2);
        title2.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        isLogin = ((GlobalApplication) getApplication()).isLogin();
        if (isLogin()) {
            user = DataWareHourse.getInstance().getmUser();
            userBean = user.getData().get(0);
        }
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        homeTaocanFragment1.onWindowFocusChanged(hasFocus);
    }

    final public static int REQUEST_CODE_ASK_CALL_PHONE = 123;

    @Override
    public void onClick(View v) {
        int index = 0;
        switch (v.getId()) {
            case R.id.shop_title1:
                index = 0;
                title1.setTextColor(getResources().getColor(R.color.colorMainRed));
                break;
            case R.id.shop_title2:
                index = 1;
                title2.setTextColor(getResources().getColor(R.color.colorMainRed));
                break;

            case R.id.iv_product_taocanExpend:
                if (!isExpend) {//如果是展开的;
                    iv_product_taocanExpend.setImageResource(R.mipmap.down_gray_48);
                    tv_product_desc.setVisibility(View.GONE);
                    tv_product_desc.setText(homedata.getNvc_Description());
                    isExpend = true;
                } else {
                    iv_product_taocanExpend.setImageResource(R.mipmap.up_gray_48);
                    tv_product_desc.setVisibility(View.VISIBLE);
                    isExpend = false;
                }
                break;
            //进入店铺
            case R.id.iv_detail_toshop:
                Intent intent = new Intent();
                intent.setClass(this, ShopDetailsActivity.class);
                intent.putExtra("nvc_num", homedata.getBusiness().getNvc_No());
                intent.putExtra("BusinessID", homedata.getBusiness().getI_Id());
                startActivity(intent);
                break;

            case R.id.tv_addcart:
                //添加购物车;
                if (isCanBuy) {
                    addCart();
                    isCanBuy = false;
                }
                break;
            case R.id.ll_me_collect:
                //添加收藏
                if (isLogin()) {
                    addCollectAndCancleCollect();
                } else {
                    showLoginDialog(BASE_REQUEST_LOGIN_CODE + 2);
                }
                break;
            //立即购买;
            case R.id.tv_addcart_buynow:
                if (isCanBuyNow) {
                    if (isLogin()) {
                        buyNow();
                    } else {
                        showLoginDialog(BASE_REQUEST_LOGIN_CODE + 4);
                    }
                    isCanBuyNow = false;
                }
                break;
            //打电话
            case R.id.tv_addcart_phone:
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
                //判断权限
                int checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE);
                if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CALL_PHONE}, REQUEST_CODE_ASK_CALL_PHONE);
                    return;
                } else {
                    showPopupWindow();
                }
                break;
            //去购物车
            case R.id.tv_addcart_cart:
                gotoCart();
                break;
            //返回键
            case R.id.product_detail_onback:
                this.finish();
                break;
            case R.id.lay_nonet:
                getHomeData();
                break;

        }
        replaceFragmet(currentTabIndex, index);
        addView();
    }

    private void addView() {
        bottomPage = new McoyProductContentPage(HomeProductdetailActivity.this, view);
        mcoySnapPageLayout.removeAllViews();
        mcoySnapPageLayout.setSnapPages(topPage, bottomPage);
    }

    @Override
    public void toNext() {
        mcoySnapPageLayout.snapToPrev();
    }

    public boolean isLogin() {
        return isLogin;
    }

    public int getProducti_id() {
        return producti_id;
    }

    private void getHomeData() {
        String url = Url.GETPRODUCTDETAIL;
        if (userBean != null) {
            url += "productId=" + producti_id + "&memberID=" + userBean.getI_Id();
        } else {
            url += "productId=" + producti_id + "&memberID=" + 0;
        }
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.GETREQUEST, url, this,
                HomeParticularsBean.class, RequestCode.GETPRODUCTDETAIL);
        HttpHandleUtil.executeCommonGet(this, httpRequestBean);
    }

    @Override
    public void onSucess(SuccessBean sucessbean) {
        Object data = sucessbean.getData();
        refreshViewLay(HAVEDATA);
        if (data instanceof HomeParticularsBean) {
            HomeParticularsBean databean = (HomeParticularsBean) data;
            switch (databean.getResCode()) {
                case "0000":
                    homedata = databean.getData();
                    i_category = homedata.getI_Category();
                    tv_nvc_Name.setText(homedata.getNvc_Name());
                    x.image().bind(iv_detailhead, homedata.getNvc_PicMain(), ImageOptionsUtil.getOptions316_720());
                    tv_nvc_StoreName.setText(homedata.getBusiness().getNvc_StoreName());
                    tv_collections.setText("粉丝: " + homedata.getBusiness().getBusinessMemberCount());
                    tv_example.setText("案例: " + homedata.getBusiness().getCasesCount());
                    x.image().bind(iv_lable_shope, homedata.getBusiness().getNvc_Logo(), ImageOptionsUtil.getcircle_fixy());
                    tv_nvc_shopName.setText(homedata.getBusiness().getNvc_Logo());
                    tv_productdetail_price.setText("" + homedata.getDm_ShopPrice());
                    tv_nvc_shopPrice.setText("¥" + homedata.getDm_Price());
                    tv_nvc_shopPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG | Paint.ANTI_ALIAS_FLAG);
                    tv_nvc_shopName.setText(homedata.getBusiness().getNvc_StoreName());
                    tv_nvc_Address.setText(homedata.getBusiness().getNvc_Address());
                    I_Show = homedata.getI_Show();
                    IsCollection = homedata.isIsCollection();
                    //判断是否收藏;
                    final boolean isCollection = homedata.isIsCollection();
                    if (isCollection) {
                        iv_me_show.setVisibility(View.VISIBLE);
                        iv_me_no.setVisibility(View.GONE);
                    } else {
                        iv_me_show.setVisibility(View.GONE);
                        iv_me_no.setVisibility(View.VISIBLE);
                    }
                    String str = homedata.getNvc_WXTS();
                    if (!TextUtils.isEmpty(str)) {
                        MessageEvent event = new MessageEvent();
                        event.setNotic(str);
                        EventBus.getDefault().post(event);
                    }
                    break;
            }
        }
        //添加购物车成功;
        else if (data instanceof AddCartResultBean) {
            isCanBuy = true;
            AddCartResultBean resultData = (AddCartResultBean) data;
            if (resultData.isResult()) {
                if ("0000".equals(resultData.getResCode())) {
                    Toast.makeText(this, "添加到购物车成功", Toast.LENGTH_SHORT).show();
                    Intent intent = new Intent();
                    intent.setAction("a66weding.com.jiehuntong.pager.CATEGURYPAGER");
                    //发送无序广播
                    sendBroadcast(intent);

                }
            } else {
                Toast.makeText(this, "添加到购物车失败", Toast.LENGTH_SHORT).show();
            }
        }

        //取消收藏
        else if (data instanceof CancelCollectBean) {
            CancelCollectBean dataBean = (CancelCollectBean) data;
            switch (dataBean.getResCode()) {
                case "0000":
                    myDialog = new MyDialog(this, "取消收藏成功!");
                    myDialog.show();
                    mHandler.sendEmptyMessageDelayed(DIALOG, 800);
                    homedata.setIsCollection(false);
                    iv_me_show.setVisibility(View.GONE);
                    iv_me_no.setVisibility(View.VISIBLE);
                    break;
            }
        }

        //添加收藏;
        else if (data instanceof MeShoppingCartDeleteBean) {
            MeShoppingCartDeleteBean dataBean = (MeShoppingCartDeleteBean) data;
            switch (dataBean.getResCode()) {
                case "0000":
                    myDialog = new MyDialog(this, "收藏成功!");
                    myDialog.show();
                    mHandler.sendEmptyMessageDelayed(DIALOG, 800);
                    homedata.setIsCollection(true);
                    iv_me_show.setVisibility(View.VISIBLE);
                    iv_me_no.setVisibility(View.GONE);
                    break;
            }
        }

        //立即购买
        else if (data instanceof CommonResultBean) {
            isCanBuyNow = true;
            CommonResultBean dataBean = (CommonResultBean) data;
            switch (dataBean.getResCode()) {
                case "0000":
                    // 跳到购物车界面
                    Intent intent = new Intent(HomeProductdetailActivity.this, MeShoppingCartActivity.class);
                    if (homedata != null) {
                        intent.putExtra("isSelectGoods", true);
                        int busessesId = homedata.getBusiness().getI_Id();
                        int i_id = homedata.getI_Id();
                        int[] selectId = {i_id, busessesId};
                        intent.putExtra("waitpayId", selectId);
                    }
                    startActivity(intent);
                    Intent intent2 = new Intent();
                    intent2.setAction("a66weding.com.jiehuntong.pager.CATEGURYPAGER");
                    //发送无序广播
                    sendBroadcast(intent2);
                    break;
            }
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        outState.putInt("index", currentTabIndex);
        super.onSaveInstanceState(outState);
    }

    @Override
    public void onError(ErrorBean errorBean) {
        isCanBuy = true;
        isCanBuyNow = true;
        switch (errorBean.getErrorCode()) {
            case ErrorBean.TIMEOUT:
                refreshViewLay(NONET);
                break;
            case ErrorBean.NONET:
                refreshViewLay(NONET);
                break;
            default:
                if (!isShowError) {
                    CUtils.showDataErrToast(this);
                    isShowError = true;
                }
        }
    }

    public int getI_category() {
        return i_category;
    }

    private void setData() {
        //返回
        product_detail_onback = (LinearLayout) topView.findViewById(R.id.product_detail_onback);
        product_detail_onback.setOnClickListener(this);
        iv_detailhead = (ImageView) topView.findViewById(R.id.iv_detailhead);
        tv_nvc_Name = (TextView) topView.findViewById(R.id.tv_nvc_Name);
        tv_nvc_StoreName = (TextView) topView.findViewById(R.id.tv_nvc_StoreName);
        tv_productdetail_price = (TextView) topView.findViewById(R.id.tv_productdetail_price);
        tv_nvc_shopPrice = (TextView) topView.findViewById(R.id.tv_nvc_shopPrice);
        iv_lable_shope = (ImageView) topView.findViewById(R.id.iv_lable_shope);
        tv_nvc_shopName = (TextView) topView.findViewById(R.id.tv_nvc_shopName);
        tv_nvc_Address = (TextView) topView.findViewById(R.id.tv_nvc_Address);
        tv_example = (TextView) topView.findViewById(R.id.tv_example);
        tv_collections = (TextView) topView.findViewById(R.id.tv_collections);
        tv_product_desc = (TextView) topView.findViewById(R.id.tv_product_desc);
        iv_product_taocanExpend = (ImageView) topView.findViewById(R.id.iv_product_taocanExpend);
        iv_product_taocanExpend.setOnClickListener(this);
        //进入店铺按钮
        iv_detail_toshop = (ImageView) topView.findViewById(R.id.iv_detail_toshop);
        iv_detail_toshop.setOnClickListener(this);
        //添加购物车
        tv_addcart = (TextView) findViewById(R.id.tv_addcart);
        tv_addcart.setOnClickListener(this);
        //收藏
        ll_me_collect = (LinearLayout) findViewById(R.id.ll_me_collect);
        ll_me_collect.setOnClickListener(this);
        //白心
        iv_me_no = (ImageView) findViewById(R.id.iv_me_no);
        //红心
        iv_me_show = (ImageView) findViewById(R.id.iv_me_show);
        //收藏成功了
        tv_addcart_buynow = (TextView) findViewById(R.id.tv_addcart_buynow);
        tv_addcart_buynow.setOnClickListener(this);
        //立即购买
        tv_addcart_phone = (TextView) findViewById(R.id.tv_addcart_phone);
        tv_addcart_phone.setOnClickListener(this);
        //购物车标题栏
        lay_cart_addcart = (LinearLayout) findViewById(R.id.lay_cart_addcart);
        //购物车图标
        tv_addcart_cart = (TextView) findViewById(R.id.tv_addcart_cart);
        tv_addcart_cart.setOnClickListener(this);

    }

    //添添加购物车;
    private void addCart() {
        if (isLogin) {
            String url = RequestCode.AddShops;
            url += "&memberID=" + DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id()
                    + "&number=" + 1 + "&productID=" + producti_id;
            if (I_Show == 0) {
                HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url, this, AddCartResultBean.class, RequestCode.AddShops);
                HttpHandleUtil.executeCommonPost(this, httpRequestBean);
            } else {
                Toast.makeText(this, "此商品已下架", Toast.LENGTH_SHORT).show();
            }
        } else {
            showLoginDialog(BASE_REQUEST_LOGIN_CODE + 3);
        }
    }


    public void showLoginDialog(final int requstLoginCode) {
        final ConfirmLoginDialog confirmDialog = new ConfirmLoginDialog(this, "亲，需要登录哦~", "去登录", "取消", R.layout.pop_tologin);
        confirmDialog.show();
        confirmDialog.setClicklistener(new ConfirmLoginDialog.ClickListenerInterface() {
            @Override
            public void doConfirm() {
                Intent intent = new Intent(HomeProductdetailActivity.this, LoginActivity.class);
                startActivityForResult(intent, requstLoginCode);
                confirmDialog.dismiss();
            }

            @Override
            public void doCancel() {
                confirmDialog.dismiss();
            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        isCanBuy = true;
        isCanBuyNow = true;
        if (resultCode==LoginActivity.LOGIN_OK){
            isLogin  = ((GlobalApplication)getApplication()).isLogin();
            if(isLogin) {
                user = DataWareHourse.getInstance().getmUser();
                if (user!=null){
                    userBean = user.getData().get(0);
                }
            }
        }
        if (requestCode == (BASE_REQUEST_LOGIN_CODE + 1) && resultCode == LoginActivity.LOGIN_OK) {
            Intent intent = new Intent();
            intent.setClass(HomeProductdetailActivity.this, MeShoppingCartActivity.class);
            startActivity(intent);
        } else if (requestCode == (BASE_REQUEST_LOGIN_CODE + 2) && resultCode == LoginActivity.LOGIN_OK) {
            getHomeData();
            addCollectAndCancleCollect();
        } else if (requestCode == (BASE_REQUEST_LOGIN_CODE + 3) && resultCode == LoginActivity.LOGIN_OK) {
            addCart();
        } else if (requestCode == (BASE_REQUEST_LOGIN_CODE + 4) && resultCode == LoginActivity.LOGIN_OK) {
            buyNow();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 收藏和取消收藏
     */
    private void addCollectAndCancleCollect() {
        if (IsCollection) {
            //取消收藏
            cancleAttention();
            IsCollection = false;
        } else {
            //添加收藏;
            addAttention();
            IsCollection = true;
        }
    }

    //取消收藏
    private void cancleAttention() {
        String oldUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.POSTCOLLECTIONCANCEL);
        String url = oldUrl + "&productID=" + homedata.getI_Id();
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                this, CancelCollectBean.class, RequestCode.POSTCOLLECTIONCANCEL);
        HttpHandleUtil.executeCommonPost(this, httpRequestBean);
    }

    //添加收藏;
    private void addAttention() {
        String oldUrl = UrlDealUtil.getRealUrlNewIdApi(RequestCode.POSTCOLLECTIONCREATE);
        String url = oldUrl + "&productID=" + homedata.getI_Id() + "&businessID="
                + homedata.getI_Business();
        HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                HomeProductdetailActivity.this, MeShoppingCartDeleteBean.class, RequestCode.POSTCOLLECTIONCREATE);
        HttpHandleUtil.executeCommonPost(HomeProductdetailActivity.this, httpRequestBean);
    }
    //打电话

    //立即购买
    private void buyNow() {
        int productId = homedata.getI_Id();
        String url = RequestCode.AddShops;
        url += "&memberID=" + DataWareHourse.getInstance().getmUser().getData().get(0).getI_Id()
                + "&number=" + 1 + "&productID=" + productId;
        if (homedata.getI_Show() == 0) {
            HttpRequestBean httpRequestBean = new HttpRequestBean(RequestCode.POSTEQUEST, url,
                    this, CommonResultBean.class, RequestCode.AddShops);
            HttpHandleUtil.executeCommonPost(this, httpRequestBean);
        }
    }

    //显示窗体
    private void showPopupWindow() {
        //设置contentView
        View contentView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.pop_home_wedreg_phone, null);
        mPopWindow = new PopupWindow(contentView, WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT, true);
        //设置各个控件的点击响应
        RelativeLayout mPhoneRaly = (RelativeLayout) contentView.findViewById(R.id.rlay_phonenum);
        RelativeLayout mCallRaly = (RelativeLayout) contentView.findViewById(R.id.rl_home_call);
        TextView mCancelTv = (TextView) contentView.findViewById(R.id.tv_telephone_cancel);
        TextView mCallPhonelTv = (TextView) contentView.findViewById(R.id.tv_firstnum);
        TextView mCallTv = (TextView) contentView.findViewById(R.id.tv_home_call);
        mCallRaly.setVisibility(View.GONE);
        String nvc_telPhone = homedata.getBusiness().getNvc_TelPhone();
        String nvc_mobilePhone = homedata.getBusiness().getNvc_MobilePhone();
        if (TextUtils.isEmpty(nvc_mobilePhone)) {
            mPhoneRaly.setVisibility(View.GONE);
        } else {
            mPhoneRaly.setVisibility(View.VISIBLE);
            mCallPhonelTv.setText(" " + homedata.getBusiness().getNvc_MobilePhone());

        }

        if (TextUtils.isEmpty(nvc_telPhone)) {
            mCallRaly.setVisibility(View.GONE);
        } else {
            mCallRaly.setVisibility(View.VISIBLE);
            mCallTv.setText("" + homedata.getBusiness().getNvc_TelPhone());
        }

        if (nvc_telPhone.equals(nvc_mobilePhone)) {
            mPhoneRaly.setVisibility(View.GONE);
        }

        mCallRaly.setOnClickListener(new View.OnClickListener() {  // 点击电话按钮
            @Override
            public void onClick(View v) {
                String call = "" + homedata.getBusiness().getNvc_TelPhone();
                Uri uri = Uri.parse("tel:" + call);
                Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intent);
            }
        });

        mPhoneRaly.setOnClickListener(new View.OnClickListener() {  // 点击手机按钮
            @Override
            public void onClick(View v) {
                String phone = "" + homedata.getBusiness().getNvc_MobilePhone();
                Uri uri = Uri.parse("tel:" + phone);
                Intent intent = new Intent(Intent.ACTION_DIAL, uri);
                startActivity(intent);
            }
        });
        mCancelTv.setOnClickListener(new View.OnClickListener() {   //点击取消按钮
            @Override
            public void onClick(View v) {
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
            }
        });

        contentView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mPopWindow != null) {
                    mPopWindow.dismiss();
                }
            }
        });

        ColorDrawable dw = new ColorDrawable(getResources().getColor(R.color.whitetranslucenthalf2));
        mPopWindow.setBackgroundDrawable(dw);
        mPopWindow.showAtLocation(lay_cart_addcart, Gravity.BOTTOM, 0, 0);
    }

    private void refreshViewLay(int state) {
        switch (state) {
            case HAVEDATA:
                if (mContentLay.isShown() && !mProgressLay.isShown()) {
                    return;
                }
                mProgressLay.setVisibility(View.GONE);
                mContentLay.setVisibility(View.VISIBLE);
                mNonetLay.setVisibility(View.GONE);
                lay_cart_addcart.setVisibility(View.VISIBLE);
                break;
            case NODATA:
                mProgressLay.setVisibility(View.VISIBLE);
                mContentLay.setVisibility(View.GONE);
                mNonetLay.setVisibility(View.GONE);
                lay_cart_addcart.setVisibility(View.GONE);
                break;
            case NONET:
                mProgressLay.setVisibility(View.GONE);
                mContentLay.setVisibility(View.GONE);
                mNonetLay.setVisibility(View.VISIBLE);
                lay_cart_addcart.setVisibility(View.GONE);
                break;
        }
    }

    private void gotoCart() {
        if (isLogin) {
            Intent intent = new Intent();
            intent.setClass(HomeProductdetailActivity.this, MeShoppingCartActivity.class);
            startActivity(intent);
        } else {
            showLoginDialog(BASE_REQUEST_LOGIN_CODE + 1);
        }
    }

    //当前角标
    private int currentTabIndex = 0;
    private Fragment[] fragments;

    protected void init(Bundle savedInstanceState) {
        if (savedInstanceState == null) {
            homeTaocanFragment1 = new ShopTuWenFragment();
            homeTaocanFragment1.setInnner(this);
            hotPackageFragment = new HotPackageFragment();
            hotPackageFragment.setInnner(this);
            getSupportFragmentManager().beginTransaction()
                    .add(R.id.shop_content, homeTaocanFragment1, ShopTuWenFragment.class.getSimpleName())
                    .add(R.id.shop_content, hotPackageFragment, HotPackageFragment.class.getSimpleName())
                    .hide(homeTaocanFragment1)
                    .hide(hotPackageFragment)
                    .show(homeTaocanFragment1)
                    .commit();
        } else {
            currentTabIndex = savedInstanceState.getInt("index");// 取出来当前第几个fragment
            FragmentManager fmg = getSupportFragmentManager();
            homeTaocanFragment1 = (ShopTuWenFragment) fmg.findFragmentByTag(ShopTuWenFragment.class.getSimpleName());
            hotPackageFragment = (HotPackageFragment) fmg.findFragmentByTag(HotPackageFragment.class.getSimpleName());
            fragments = new Fragment[]{homeTaocanFragment1, hotPackageFragment};
            fmg.beginTransaction()
                    .hide(homeTaocanFragment1)
                    .hide(hotPackageFragment)
                    .show(fragments[currentTabIndex])
                    .commit(); // 显示以前报错的fragment
            replaceFragmet(0, currentTabIndex);
        }
        fragments = new Fragment[]{homeTaocanFragment1, hotPackageFragment};
    }

    public void replaceFragmet(int oldIndex, int newIndex) {
        if (newIndex != oldIndex) {
            FragmentTransaction trx = getSupportFragmentManager().beginTransaction();
            trx.hide(fragments[oldIndex]);
            trx.show(fragments[newIndex]).commit();
            currentTabIndex = newIndex;
            setTabSelect(currentTabIndex);
        }
    }

    private void setTabSelect(int currentTabIndex) {
        switch (currentTabIndex) {
            case 0:
                title1.setTextColor(getResources().getColor(R.color.colorMainRed));
                title2.setTextColor(getResources().getColor(R.color.line));
                break;
            case 1:
                title2.setTextColor(getResources().getColor(R.color.colorMainRed));
                title1.setTextColor(getResources().getColor(R.color.line));
                break;
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_CALL_PHONE:
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    showPopupWindow();
                } else {
                    Toast.makeText(this, "请设置电话权限", Toast.LENGTH_SHORT)
                            .show();
                }
                break;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
